package com.app.h5;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.app.h5.databinding.ActivityWebViewBinding;
import com.app.h5.databinding.LayoutFloatButtonBinding;
import com.app.h5.pic.MeOnResultCallbackListener;
import com.app.h5.pic.MediaPickerUtil;
import com.app.h5.util.BottomMediaDialog;
import com.app.h5.util.PopView;
import com.app.h5.util.SPUtil;
import com.app.h5.util.SonnyJackDragView;
import com.app.h5.util.UIUtil;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import static com.app.h5.SplashActivity.H5_URLS;

/**
 * PackageName  com.kincho.sportreview
 * ProjectName  Eagle-eye
 * Date         2024/9/25.
 *
 * @author neo
 */

public class WebViewActivity extends AppCompatActivity {
    public static final String TAG = "WebViewActivity";
    private String url;
    private ActivityWebViewBinding binding;
    private PopView popView;
    private final Handler handler = new Handler();
    private ValueCallback<Uri[]> filePathCallback;
    private BottomMediaDialog dialog;
    private final Runnable runnableNav = new Runnable() {
        @Override
        public void run() {
            if (binding.webView.canGoBack()) {
                binding.webView.goBack();
                handler.removeCallbacks(this);
                handler.postDelayed(this, 100);
            }
        }
    };
    private int time;
    private boolean startProgress;
    private final Runnable runnableTimer = new Runnable() {
        @Override
        public void run() {
            time++;
            Log.d("OK_LOG", "time = " + time);
            handler.removeCallbacks(this);
            if (time >= 10) {
                time = 0;
                startProgress = false;
                showBtn();
            } else {
                handler.postDelayed(this, 1000);
            }
        }
    };

    private void showBtn() {
        Log.d("OK_LOG", "time out");
        binding.ivReload.setVisibility(View.VISIBLE);
        binding.ivReload.setOnClickListener(v -> {
            binding.ivReload.setVisibility(View.GONE);
            getUrl(false);
            //添加参数 terminals=6
            binding.webView.loadUrl(url);
        });
    }

    public static void toWebViewActivity(Activity activity) {
        Intent intent = new Intent(activity, WebViewActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityWebViewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
        initView();
        binding.getRoot().post(this::initDragBtn);
    }

    private void initDragBtn() {
        LayoutFloatButtonBinding floatBtn = LayoutFloatButtonBinding.inflate(getLayoutInflater());
        floatBtn.getRoot().setOnClickListener(v -> {
            // Toast.makeText(this, "点击了...", Toast.LENGTH_SHORT).show();
            if (popView != null) {
                if (popView.isShowing()) {
                    popView.dismiss();
                } else {
                    popView.show(floatBtn.getRoot());
                    darkenBackground(0.5f);
                }
                return;
            }
            popView = new PopView(this, new PopView.OnPopClickListener() {
                @Override
                public void onClickBack() {
                    if (binding.webView.canGoBack()) {
                        binding.webView.goBack();
                    }
                    popView.dismiss();
                }

                @Override
                public void onClickFresh() {
                    binding.webView.loadUrl(url);
                    popView.dismiss();
                }

                @Override
                public void onClickGoOut() {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    popView.dismiss();
                }

                @Override
                public void onClickGoHome() {
                    handler.postDelayed(runnableNav, 100);
                    popView.dismiss();
                }
            });
            popView.setOnDismissListener(() -> darkenBackground(1f));
            popView.show(floatBtn.getRoot());
            darkenBackground(0.5f);
        });
        // 配置拖动效果
        int width = binding.webView.getWidth();
        int height = binding.webView.getHeight();
        new SonnyJackDragView.Builder()
                .setActivity(this)//当前Activity，不可为空
                .setDefaultLeft(width - UIUtil.dip2px(this, 80))//初始位置左边距
                .setDefaultTop(height - UIUtil.dip2px(this, 100))//初始位置上边距
                .setNeedNearEdge(true)//拖动停止后，是否移到边沿
                //.setSize(200)//DragView大小
                .setView(floatBtn.getRoot())//设置自定义的DragView，切记不可为空
                //.setNeedNearEdge(false)
                .build();
    }

    private void darkenBackground(Float bgcolor) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgcolor;
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        window.setAttributes(lp);
    }

    private void initView() {
        initWebView(binding.webView);
        binding.webView.setWebChromeClient(chromeClient);
        binding.webView.loadUrl(url);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView(WebView webView) {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//支持js调用window.open方法
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setSupportMultipleWindows(false);// 设置允许开启多窗口,实际上设置false就会避免新建窗口操作,不用将问题复杂化
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);// 设置支持javascript
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAllowContentAccess(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                // return false;
            }
        });
    }

    WebChromeClient chromeClient = new WebChromeClient() {
        @SuppressLint("ObsoleteSdkInt")
        @Override
        public void onProgressChanged(WebView webView, int i) {
            super.onProgressChanged(webView, i);
            Log.d(TAG, "onProgressChanged progress=" + i);
            binding.progressBar.setVisibility(View.VISIBLE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                binding.progressBar.setProgress(i, true);
            } else {
                binding.progressBar.setProgress(i);
            }
            if (i == 100) {
                time = 0;
                startProgress = false;
                binding.ivReload.setVisibility(View.GONE);
                binding.progressBar.setVisibility(View.INVISIBLE);
                handler.removeCallbacks(runnableTimer);
            } else {
                if (notSingleUrl()) {
                    if (!startProgress) {
                        startProgress = true;
                        handler.postDelayed(runnableTimer, 1000);
                    }
                } else {
                    Log.d("OK_LOG", "urls 1");
                }
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            //return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            WebViewActivity.this.filePathCallback = filePathCallback;
            chooseMedia();
            return true;
        }
    };

    private void chooseMedia() {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog.show();
            return;
        }
        dialog = new BottomMediaDialog(this, new BottomMediaDialog.SelectListener() {
            @Override
            public void pic() {
                getPhoto();
            }

            @Override
            public void video() {
                getVideo();
            }

            @Override
            public void cancel() {
                callBack(null);
            }
        });
        dialog.show();
    }

    private void getVideo() {
        MediaPickerUtil.getMedia(this, SelectMimeType.ofVideo(), false, false, true, false, 1, new MeOnResultCallbackListener() {
            @Override
            public void onResult(ArrayList<LocalMedia> result) {
                if (result != null && !result.isEmpty()) {
                    Uri[] uris = new Uri[result.size()];
                    for (int i = 0; i < result.size(); i++) {
                        uris[i] = Uri.fromFile(new File(result.get(i).getAvailablePath()));
                    }
                    callBack(uris);
                } else {
                    callBack(null);
                }
            }

            @Override
            public void onCancel() {
                super.onCancel();
                callBack(null);
            }
        });
    }

    private void getPhoto() {
        MediaPickerUtil.getMedia(this, SelectMimeType.ofImage(), false, false, true, false, 1, new MeOnResultCallbackListener() {
            @Override
            public void onResult(ArrayList<LocalMedia> result) {
                if (result != null && !result.isEmpty()) {
                    Uri[] uris = new Uri[result.size()];
                    for (int i = 0; i < result.size(); i++) {
                        uris[i] = Uri.fromFile(new File(result.get(i).getAvailablePath()));
                    }
                    callBack(uris);
                } else {
                    callBack(null);
                }
            }

            @Override
            public void onCancel() {
                super.onCancel();
                // 这里很重要,web一旦触发了选文件方法,原生这边不管有没有执行操作,都要回调,即便是直接回调null,不能省略
                callBack(null);
            }
        });
    }

    private void callBack(Uri[] uris) {
        if (filePathCallback != null) {
            filePathCallback.onReceiveValue(uris);
            filePathCallback = null;
        }
    }

    private void init() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.statusBarColor)
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                //.navigationBarColor(R.color.transparent)
                //.navigationBarDarkIcon(isDarkTheme())
                .init();
        getUrl(false);
    }

    private void getUrl(boolean next) {
        List<String> urls = SPUtil.getList(H5_URLS, String.class);
        if (!next) {
            url = urls.get(0);
        } else {
            int index = urls.indexOf(url) + 1;
            if (index < urls.size()) {
                url = urls.get(index);
            } else {
                url = urls.get(0);
            }
        }
    }

    private boolean notSingleUrl() {
        return SPUtil.getList(H5_URLS, String.class).size() > 1;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (binding.webView.canGoBack()) {
                binding.webView.goBack();
            } else {
                Toast.makeText(this, "不能返回了~", Toast.LENGTH_SHORT).show();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnableNav);
        handler.removeCallbacks(runnableTimer);
        binding.webView.setWebViewClient(null);
        binding.webView.setWebChromeClient(null);
        binding.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        binding.webView.clearHistory();
        binding.webView.destroy();
    }
}
